"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import Resource
from flask import jsonify,request,jsonify
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from flask_jwt_extended import jwt_required
from apps.API.auth.util import hash_pass
from apps.API.auth.models import Users,Role
from apps.API.electricSigature.AuditRecord import Part11AuditRecord as Arecord
from apps import db
'''/api/user/User'''
class interfaceUser(Resource):
    @jwt_required()
    def get(self):
        # try:
            tmp_info=db.session.query(Users,Role).outerjoin(Role,Users.role_id==Role.name).all()
            base_info=[]
            for user,role in tmp_info:
                user_info=user.to_dict()
                role_info=role.to_dict()
                if user_info["username"] == 'admin':
                    pass
                else:
                    base_info.append({
                        "id":user_info["id"],
                        "username":user_info["username"],
                        "email":user_info["email"],
                        "role_id":user_info["role_id"],
                        "group": role_info["group"],
                        "detail":role_info["detail"],
                        "create_time":user_info["create_time"]
                    })            
            response=jsonify(base_info)
            response.status=202
            return response
        # except Exception as e:
        #     lg.error(e)
        #     return 400
    @jwt_required()
    def post(Resource):
        try:
            ## SQL: insert User script ###
            username=request.json["username"]
            email=request.json["email"]
            role_id=request.json["details"].split(":")[0]
            password=hash_pass(request.json["password"]).decode()
            cols= '''username,email,role_id,password'''
            value=f'''\"{username}\",\"{email}\",\"{role_id}\",\"{password}\"'''
            ## SQL: add user sql ###
            add_user_sql = f'''INSERT INTO users ({cols}) VALUES ({value})'''
            add_info(add_user_sql)
            ### 添加 用户到审计追踪名单 ###
            user=Users.query.filter(Users.username==request.json["username"]).first()
            id=user.id
            Arecord.audit_add_user(
                user_id=f'{username}_{id}',
                name=username,
                role=role_id,
                password=password
            )
            return 202
        except Exception as e:
            lg.error(e)
            return 400

class interfaceUserID(Resource):
    @jwt_required()
    def post(self,id):
        try:
            ### SQL: delete user in database ###
            Users.query.filter(Users.username==request.json["username"]).delete()
            db.session.commit()
            return 202
        except Exception as e:
            lg.error(e)
            
class interfaceRole(Resource):
    @jwt_required()
    def get(self):
        try:
            cols = '''id,name,detail,permissions'''
            ### SQL: query role infos ###
            role_info_sql =f'''SELECT {cols} FROM roles '''
            base_info=dic_query_info(role_info_sql)
            role_info = []
            for info in base_info:
                if info["name"] == 'R990':
                    pass
                else:
                    role_info.append(info)
            response=jsonify(role_info)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)